package com.zoke.dappstore.tools;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;

import com.zoke.dappstore.R;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;

public class UpdateService extends Service {

    /**
     * 目标文件存储的文件夹路径
     */
    private String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File
            .separator + "dapp/apk/";
    /**
     * 目标文件存储的文件名
     */
    private String destFileName = "DappStore.apk";

    private Context mContext;
    private int preProgress = 0;
    private int NOTIFY_ID = 1000;
    private NotificationCompat.Builder builder;
    private NotificationManager notificationManager;
    private Notification notification;

    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;
        if (intent == null) {
            stopSelf();
        }
        String url = intent.getStringExtra("apkUrl");
        if(!TextUtils.isEmpty(url))
            loadFile(url);
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 下载文件
     */
    private void loadFile(String url) {

        RequestParams params = new RequestParams(url);
        params.setAutoResume(true);
        params.setAutoRename(true);
        params.setSaveFilePath(destFileDir+destFileName);
        params.setCancelFast(true);
        x.http().get(params, new Callback.ProgressCallback<File>() {

            @Override
            public void onSuccess(File result) {
                notifyUser("下载完成", "下载完成", 100);
                stopSelf();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                notifyUser("下载失败", "下载失败", 0);
                stopSelf();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onWaiting() {

            }

            @Override
            public void onStarted() {

            }

            @Override
            public void onLoading(long total, long current, boolean isDownloading) {
                int progress = (int) ((current / (double) total) * 100);
                Log.e("onProgressChanged", progress + "");
                notifyUser("正在下载", "正在下载", progress);
            }
        });

    }


    private void notifyUser(String result, String msg, int progress) {

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_logo)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_logo))
                .setContentTitle(getString(R.string.app_name));
        if (progress > 0 && progress <= 100) {

            builder.setProgress(100, progress, false);

        } else {
            builder.setProgress(0, 0, false);
        }
        //自动管理通知栏消息
        builder.setAutoCancel(true);
        //使用默认提示音
//        builder.setDefaults(Notification.DEFAULT_ALL);
        builder.setWhen(System.currentTimeMillis());
        builder.setTicker(result);
        builder.setContentTitle(getResources().getString(R.string.app_name) + "  " + msg);
        builder.setContentIntent(progress >= 100 ? getContentIntent() :
                PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT));
        notification = builder.build();
        notificationManager.notify(0, notification);

    }

    private PendingIntent getContentIntent() {
        Log.e("tag", "getContentIntent()");
        File apkFile = new File(destFileDir,destFileName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N){
            Uri uriForFile = FileProvider.getUriForFile(this, "com.tdp.ushop.fileprovider", apkFile);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uriForFile, this.getContentResolver().getType(uriForFile));
        }else{
            intent.setDataAndType(Uri.parse("file://" + apkFile.getAbsolutePath()), "application/vnd.android.package-archive");
        }

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        startActivity(intent);
        return pendingIntent;
    }

}
